package service

import (
	"encoding/json"
	"log"
	"miao/config"
	"miao/dao"
	"miao/dto"
	"miao/models"
	"miao/util"
	"time"

	"golang.org/x/crypto/bcrypt"
)

// Login 用户登录
func Login(loginDto dto.LoginDTO) util.Result {
	user, err := dao.GetUserbyUsername(loginDto.Username)
	if err != nil {
		return util.Fail(500, "账号不存在")
	}
	if user.Username == "" {
		return util.Fail(500, "账号不存在")
	}
	if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(loginDto.Password)) != nil {
		return util.Fail(403, "密码错误")
	}
	roles, _ := dao.GetUserRoleByUserId(user.Id)
	authDto := dto.GetAuthDTO(&user, roles)
	userJson, _ := json.Marshal(authDto)
	token := util.GenerateToken()
	redisError := config.SetValueByTime("token:"+token, userJson, 60*60*24, time.Second)
	if redisError != nil {
		log.Println("redis set redisError:", redisError)
		return util.Fail(500, "token存储失败")
	}
	return util.Success(token)
}

// Register 用户注册
func Register(dto dto.LoginDTO) util.Result {
	user, err := dao.GetUserbyUsername(dto.Username)
	if err != nil {
		return util.Fail(500, "账号已存在")
	}
	if user.Username != "" {
		return util.Fail(500, "账号已存在")
	}
	hashPassword, _ := bcrypt.GenerateFromPassword([]byte(dto.Password), bcrypt.DefaultCost)
	id := util.GenerateSnowflakeId()
	userBase := models.UserBase{
		Username: dto.Username,
		Password: string(hashPassword),
		Id:       id,
	}

	result := config.DB.Create(&userBase)
	if result.Error != nil {
		return util.Fail(500, "注册失败")
	}
	return util.Success("注册成功")

}

// Page 分页查询用户
func Page(currentPage int, pageSize int, username string) util.Result {
	users, total, err := dao.Page(currentPage, pageSize, username)
	if err != nil {
		return util.Fail(500, "查询失败")
	}
	pageData := models.PageData{
		Total: total,
		List:  users,
	}
	return util.Success(pageData)
}

// DeleteUser 删除用户
func DeleteUser(userId string) util.Result {
	err := dao.DeleteUser(userId)
	if err != nil {
		return util.Fail(500, "删除失败")
	}
	return util.Success("删除成功")
}

// SaveUser 保存用户
func SaveUser(user *dto.UserDto) util.Result {
	user.Id = util.GenerateSnowflakeId()
	userBase := models.UserBase{
		Username: user.Username,
		Password: user.Password,
		Email:    user.Email,
		Nickname: user.Nickname,
	}
	hashPassword, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	userBase.Password = string(hashPassword)
	err := dao.SaveUser(&userBase)
	if err != nil {
		return util.Fail(500, "保存失败")
	}
	return util.Success("保存成功")
}

// GetInfo 获取用户角色
func GetInfo() util.Result {
	var userDto = util.GetValue("userInfo").(dto.UserDto)
	if userDto.Username == "" {
		return util.Fail(500, "用户信息不存在")
	}
	return util.Success(userDto)
}
